﻿#region Using Directives

using System;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.Practices.RecipeFramework.VisualStudio;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using EnvDTE;
using System.Xml;
using EnvDTE80;

#endregion

namespace SteriaMummert.SharePoint.SoftwareFactoryLite.Actions
{
    [ServiceDependency(typeof(DTE))]
    public class SaveApplicationConfiguration : ConfigurableAction
    {
        [Input(Required = true)]
        public object KeyValue
        {
            get { return _KeyValue; }
            set { _KeyValue = value; }
        }
        private object _KeyValue = null;

        [Input(Required = true)]
        public string KeyName
        {
            get { return _KeyName; }
            set { _KeyName = value; }
        }
        private string _KeyName = "";

        private XmlDocument GetApplicationConfiguration(DTE dte)
        {
            //create file if not exists
            string solutionDirectory = Path.GetDirectoryName((string)dte.Solution.Properties.Item("Path").Value);
            string toPath = Path.Combine(solutionDirectory, "ApplicationConfiguration.xml");

            if (File.Exists(toPath))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(toPath);
                return doc;
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                return doc;
            }
        }

        public override void Execute()
        {
            DTE dte = GetService<DTE>(true);

            string solutionDirectory = Path.GetDirectoryName((string)dte.Solution.Properties.Item("Path").Value);
            string toPath = Path.Combine(solutionDirectory, "ApplicationConfiguration.xml");


            //get xmldocument
            XmlDocument doc = GetApplicationConfiguration(dte);

            //hat das dokument den <ApplicationConfiguration> Tag
            XmlNode rootnode = doc.SelectSingleNode("/ApplicationConfiguration");
            if (rootnode == null)
            {
                //document ist leer, erstellen
                XmlNode root = doc.CreateElement("ApplicationConfiguration");
                doc.AppendChild(root);

                XmlNode confignode = doc.CreateElement(_KeyName);
                if (_KeyValue != null)
                {
                    confignode.InnerText = _KeyValue.ToString();
                }
                root.AppendChild(confignode);
            }
            else
            {
                //rootnode existiert
                //existiert die ConfigNode bereits und ich muss den Wert ändern?
                XmlNode configchecknode = doc.SelectSingleNode("/ApplicationConfiguration/" + _KeyName);
                if (configchecknode == null)
                {   //existiert noch nicht
                    XmlNode confignode = doc.CreateElement(_KeyName);
                    if (_KeyValue != null)
                    {
                        confignode.InnerText = _KeyValue.ToString();
                    }
                    rootnode.AppendChild(confignode);
                }
                else
                {   //node existiert, value ändern
                    if (_KeyValue != null)
                    {
                        configchecknode.InnerText = _KeyValue.ToString();
                    }
                }
            }
                        
            //save xml to the location
            doc.Save(toPath);


            //add item to the solution
            Solution2 sol = (Solution2)dte.Solution;
            try
            {
                //hat es schon das Item?
                bool fileexists = false;
                foreach (Project p in sol.Projects)
                {
                    foreach (ProjectItem pi in p.ProjectItems)
                    {
                        if (pi.Name.ToUpper() == "ApplicationConfiguration.xml".ToUpper())
                        {
                            fileexists = true;
                        }
                    }
                }
                if (!fileexists)
                {
                    //add item to folder
                    Project prjSolItems = sol.AddSolutionFolder("Solution Items");
                    dte.ItemOperations.AddExistingItem(toPath);
                }

                if (!fileexists)
                {
                    dte.ActiveWindow.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }            
        }

        /// <summary>
        /// Removes the previously added reference, if it was created
        /// </summary>
        public override void Undo()
        {
        }
    }
}